import { Card, Table, Tag, Button, Space, Modal, Form, Input, Select, DatePicker, message, Row, Col, Typography, Descriptions, Upload, InputNumber, Tabs, Divider, Steps } from '@/utils/antd-imports';
import { EyeOutlined, CheckOutlined, CloseOutlined, FileTextOutlined, UploadOutlined, AuditOutlined, UserOutlined } from '@/utils/icons';
import React, { useState } from 'react';
import moment from 'moment';

const { Option } = Select;
const { Text, Title } = Typography;
const { TextArea } = Input;
const { TabPane } = Tabs;

// 模拟开票审批数据
const generateInvoiceApprovalData = () => {
  const data = [];
  const statuses = ['待审批', '已通过', '已拒绝', '已撤回'];
  const invoiceTypes = ['增值税专用发票', '增值税普通发票', '电子发票'];
  const projects = ['项目A', '项目B', '项目C', '项目D'];
  
  for (let i = 1; i <= 20; i++) {
    data.push({
      id: i,
      invoiceNo: `INV${String(i).padStart(6, '0')}`,
      projectName: projects[Math.floor(Math.random() * projects.length)],
      projectCode: `PRJ${String(i).padStart(6, '0')}`,
      customerName: `客户${i}`,
      invoiceType: invoiceTypes[Math.floor(Math.random() * invoiceTypes.length)],
      invoiceAmount: Math.floor(Math.random() * 100000) + 10000,
      taxRate: 0.13,
      taxAmount: Math.floor(Math.random() * 10000) + 1000,
      totalAmount: Math.floor(Math.random() * 110000) + 11000,
      applicant: `申请人${i}`,
      applyTime: moment().subtract(Math.floor(Math.random() * 30), 'days').format('YYYY-MM-DD HH:mm:ss'),
      approver: i % 3 === 0 ? '财务经理' : null,
      approveTime: i % 3 === 0 ? moment().subtract(Math.floor(Math.random() * 10), 'days').format('YYYY-MM-DD HH:mm:ss') : null,
      status: statuses[Math.floor(Math.random() * statuses.length)],
      remark: i % 3 === 0 ? '发票信息完整，同意开票' : '',
      attachments: i % 2 === 0 ? [`发票申请表${i}.pdf`, `合同文件${i}.pdf`] : [],
      rejectReason: i % 5 === 0 ? '发票信息不完整，请补充相关材料' : ''
    });
  }
  
  return data;
};

const InvoiceApproval = () => {
  const [invoices, setInvoices] = useState(generateInvoiceApprovalData());
  const [modalVisible, setModalVisible] = useState(false);
  const [currentInvoice, setCurrentInvoice] = useState(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [selectedStatus, setSelectedStatus] = useState('');
  const [selectedType, setSelectedType] = useState('');

  // 筛选数据
  const filteredInvoices = invoices.filter(invoice => {
    const matchesSearch = invoice.invoiceNo.includes(searchText) || 
                         invoice.projectName.includes(searchText) ||
                         invoice.customerName.includes(searchText) ||
                         invoice.applicant.includes(searchText);
    const matchesStatus = !selectedStatus || invoice.status === selectedStatus;
    const matchesType = !selectedType || invoice.invoiceType === selectedType;
    
    return matchesSearch && matchesStatus && matchesType;
  });

  // 处理审批
  const handleApprove = (invoice, action) => {
    setCurrentInvoice(invoice);
    form.resetFields();
    if (action === 'reject') {
      form.setFieldsValue({ action: 'reject' });
    } else {
      form.setFieldsValue({ action: 'approve' });
    }
    setModalVisible(true);
  };

  // 提交审批
  const handleSubmit = () => {
    form.validateFields().then(values => {
      const { action, remark } = values;
      const updatedInvoice = {
        ...currentInvoice,
        status: action === 'approve' ? '已通过' : '已拒绝',
        approver: '当前用户',
        approveTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        remark: remark || '',
        rejectReason: action === 'reject' ? remark : ''
      };

      setInvoices(invoices.map(invoice => 
        invoice.id === currentInvoice.id ? updatedInvoice : invoice
      ));
      
      message.success(action === 'approve' ? '审批通过' : '审批拒绝');
      setModalVisible(false);
      form.resetFields();
    });
  };

  // 查看详情
  const viewDetails = (invoice) => {
    setCurrentInvoice(invoice);
    setModalVisible(true);
  };

  // 表格列定义
  const columns = [
    {
      title: '发票编号',
      dataIndex: 'invoiceNo',
      key: 'invoiceNo',
      width: 120,
      render: (text) => <Text strong>{text}</Text>
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 150
    },
    {
      title: '项目编码',
      dataIndex: 'projectCode',
      key: 'projectCode',
      width: 120
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 150
    },
    {
      title: '发票类型',
      dataIndex: 'invoiceType',
      key: 'invoiceType',
      width: 120,
      render: (type) => <Tag color="blue">{type}</Tag>
    },
    {
      title: '发票金额',
      dataIndex: 'invoiceAmount',
      key: 'invoiceAmount',
      width: 120,
      render: (amount) => `¥${amount.toLocaleString()}`
    },
    {
      title: '税率',
      dataIndex: 'taxRate',
      key: 'taxRate',
      width: 80,
      render: (rate) => `${(rate * 100).toFixed(1)}%`
    },
    {
      title: '税额',
      dataIndex: 'taxAmount',
      key: 'taxAmount',
      width: 120,
      render: (amount) => `¥${amount.toLocaleString()}`
    },
    {
      title: '总金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 120,
      render: (amount) => <Text strong>¥{amount.toLocaleString()}</Text>
    },
    {
      title: '申请人',
      dataIndex: 'applicant',
      key: 'applicant',
      width: 100
    },
    {
      title: '申请时间',
      dataIndex: 'applyTime',
      key: 'applyTime',
      width: 150
    },
    {
      title: '审批人',
      dataIndex: 'approver',
      key: 'approver',
      width: 100,
      render: (text) => text || '-'
    },
    {
      title: '审批时间',
      dataIndex: 'approveTime',
      key: 'approveTime',
      width: 150,
      render: (text) => text || '-'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const colors = {
          '待审批': 'orange',
          '已通过': 'green',
          '已拒绝': 'red',
          '已撤回': 'gray'
        };
        return <Tag color={colors[status]}>{status}</Tag>;
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            icon={<EyeOutlined />}
            onClick={() => viewDetails(record)}
          >
            查看
          </Button>
          {record.status === '待审批' && (
            <>
              <Button 
                type="link" 
                icon={<CheckOutlined />}
                onClick={() => handleApprove(record, 'approve')}
                style={{ color: '#52c41a' }}
              >
                通过
              </Button>
              <Button 
                type="link" 
                icon={<CloseOutlined />}
                onClick={() => handleApprove(record, 'reject')}
                danger
              >
                拒绝
              </Button>
            </>
          )}
        </Space>
      )
    }
  ];

  // 筛选不同状态的发票
  const pendingInvoices = invoices.filter(item => item.status === '待审批');
  const processedInvoices = invoices.filter(item => item.status !== '待审批');
  const myInitiatedInvoices = invoices.filter(item => item.applicant === '申请人1'); // 假设当前用户是申请人1

  const [selectedInvoice, setSelectedInvoice] = useState(null);
  const [activeTab, setActiveTab] = useState('pending');

  // 根据当前激活的标签页选择显示的数据
  const getTableData = () => {
    switch (activeTab) {
      case 'pending':
        return pendingInvoices;
      case 'processed':
        return processedInvoices;
      case 'myInitiated':
        return myInitiatedInvoices;
      default:
        return invoices;
    }
  };

  const showDetail = (record) => {
    setSelectedInvoice(record);
  };

  return (
    <div style={{ backgroundColor: '#f5f5f5', minHeight: '100vh', padding: 16 }}>
      {/* 顶部卡片式Tab */}
      <Card style={{ marginBottom: 16 }}>
        <Tabs 
          type="card" 
          activeKey={activeTab} 
          onChange={setActiveTab}
        >
          <TabPane 
            tab={
              <span>
                <AuditOutlined />
                待处理的 ({pendingInvoices.length})
              </span>
            } 
            key="pending"
          />
          <TabPane 
            tab={
              <span>
                <CheckOutlined />
                已处理的
              </span>
            } 
            key="processed"
          />
          <TabPane 
            tab={
              <span>
                <UserOutlined />
                我发起的
              </span>
            } 
            key="myInitiated"
          />
        </Tabs>

        <div style={{ display: 'flex', gap: 16 }}>
          {/* 左侧发票列表 */}
          <div style={{ width: 380, flexShrink: 0 }}>
            <Card 
              title="开票审批列表"
              bordered={false}
              style={{ boxShadow: '0 1px 3px rgba(0,0,0,0.1)', height: '100%' }}
            >
              <div style={{ overflowY: 'auto', height: 'calc(100vh - 220px)' }}>
                {getTableData().map(invoice => (
                  <Card 
                    key={invoice.id}
                    style={{ 
                      marginBottom: 16, 
                      cursor: 'pointer',
                      borderLeft: selectedInvoice?.id === invoice.id ? '3px solid #1890ff' : '1px solid #f0f0f0'
                    }}
                    onClick={() => showDetail(invoice)}
                  >
                    <div>
                      <h4 style={{ marginBottom: 8 }}>{invoice.invoiceNo}</h4>
                      <Tag color={invoice.status === '待审批' ? 'orange' : invoice.status === '已通过' ? 'green' : 'red'}>
                        {invoice.status}
                      </Tag>
                      <div style={{ color: '#666', fontSize: 12, marginTop: 8 }}>申请人: {invoice.applicant}</div>
                    </div>
                    <Divider style={{ margin: '12px 0' }} />
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                      <div>
                        <div style={{ color: '#666', fontSize: 12 }}>发票金额</div>
                        <div>¥{invoice.invoiceAmount.toLocaleString()}</div>
                      </div>
                      <div>
                        <div style={{ color: '#666', fontSize: 12 }}>申请时间</div>
                        <div>{invoice.applyTime}</div>
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
            </Card>
          </div>

          {/* 右侧审批内容 - 主要区域 */}
          <div style={{ flex: 1 }}>
            {selectedInvoice ? (
              <Card 
                title={`${selectedInvoice.applicant}提交的${selectedInvoice.invoiceNo}`}
                bordered={false}
                style={{ boxShadow: '0 1px 3px rgba(0,0,0,0.1)', height: '100%' }}
                extra={
                  <Space>
                    <Tag color={selectedInvoice.status === '待审批' ? 'orange' : selectedInvoice.status === '已通过' ? 'green' : 'red'}>
                      {selectedInvoice.status}
                    </Tag>
                    {selectedInvoice.status === '待审批' && (
                      <Space>
                        <Button 
                          type="primary" 
                          icon={<CheckOutlined />} 
                          onClick={() => handleApprove(selectedInvoice, 'approve')}
                        >
                          通过
                        </Button>
                        <Button 
                          danger 
                          icon={<CloseOutlined />} 
                          onClick={() => handleApprove(selectedInvoice, 'reject')}
                        >
                          拒绝
                        </Button>
                      </Space>
                    )}
                  </Space>
                }
              >
                <div style={{ display: 'flex', gap: 24, height: 'calc(100vh - 220px)', overflowY: 'auto' }}>
                  {/* 左侧发票详情 */}
                  <div style={{ flex: 1 }}>
                    <h3>发票详情</h3>
                    <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: '12px 0', alignItems: 'center' }}>
                      <div style={{ fontWeight: 'bold', color: '#666' }}>发票编号</div>
                      <div>{selectedInvoice.invoiceNo}</div>
                      
                      <div style={{ fontWeight: 'bold', color: '#666' }}>项目名称</div>
                      <div>{selectedInvoice.projectName}</div>
                      
                      <div style={{ fontWeight: 'bold', color: '#666' }}>项目编码</div>
                      <div>{selectedInvoice.projectCode}</div>
                      
                      <div style={{ fontWeight: 'bold', color: '#666' }}>客户名称</div>
                      <div>{selectedInvoice.customerName}</div>
                      
                      <div style={{ fontWeight: 'bold', color: '#666' }}>发票类型</div>
                      <div>{selectedInvoice.invoiceType}</div>
                      
                      <div style={{ fontWeight: 'bold', color: '#666' }}>发票金额</div>
                      <div>¥{selectedInvoice.invoiceAmount.toLocaleString()}</div>
                      
                      <div style={{ fontWeight: 'bold', color: '#666' }}>税率</div>
                      <div>{(selectedInvoice.taxRate * 100).toFixed(1)}%</div>
                      
                      <div style={{ fontWeight: 'bold', color: '#666' }}>税额</div>
                      <div>¥{selectedInvoice.taxAmount.toLocaleString()}</div>
                      
                      <div style={{ fontWeight: 'bold', color: '#666' }}>总金额</div>
                      <div><Text strong>¥{selectedInvoice.totalAmount.toLocaleString()}</Text></div>
                      
                      <div style={{ fontWeight: 'bold', color: '#666' }}>申请人</div>
                      <div>{selectedInvoice.applicant}</div>
                      
                      <div style={{ fontWeight: 'bold', color: '#666' }}>申请时间</div>
                      <div>{selectedInvoice.applyTime}</div>
                      
                      <div style={{ fontWeight: 'bold', color: '#666' }}>审批人</div>
                      <div>{selectedInvoice.approver || '-'}</div>
                      
                      <div style={{ fontWeight: 'bold', color: '#666' }}>审批时间</div>
                      <div>{selectedInvoice.approveTime || '-'}</div>
                    </div>
                    
                    {selectedInvoice.attachments && selectedInvoice.attachments.length > 0 && (
                      <>
                        <Divider />
                        <h3>相关附件</h3>
                        <Space wrap>
                          {selectedInvoice.attachments.map((file, index) => (
                            <Button key={index} type="link" icon={<FileTextOutlined />}>
                              {file}
                            </Button>
                          ))}
                        </Space>
                      </>
                    )}

                    {selectedInvoice.rejectReason && (
                      <>
                        <Divider />
                        <h3>拒绝原因</h3>
                        <Text type="danger">{selectedInvoice.rejectReason}</Text>
                      </>
                    )}
                  </div>
                  
                  {/* 右侧审批流程 */}
                  <div style={{ width: 500 }}>
                    <h3>审批流程</h3>
                    <Steps 
                      direction="vertical" 
                      size="small" 
                      current={selectedInvoice.status === '待审批' ? 0 : selectedInvoice.status === '已通过' ? 2 : 1}
                      items={[
                        {
                          title: '提交申请',
                          description: (
                            <div>
                              <div>{selectedInvoice.applicant}</div>
                              <div style={{ color: '#999', fontSize: 12 }}>{selectedInvoice.applyTime}</div>
                            </div>
                          ),
                          status: 'finish'
                        },
                        {
                          title: '财务审批',
                          description: (
                            <div>
                              <div>{selectedInvoice.approver || '等待审批'}</div>
                              {selectedInvoice.approveTime && (
                                <div style={{ color: '#999', fontSize: 12 }}>{selectedInvoice.approveTime}</div>
                              )}
                            </div>
                          ),
                          status: selectedInvoice.status === '待审批' ? 'process' : selectedInvoice.status === '已通过' ? 'finish' : 'error',
                          subTitle: selectedInvoice.remark && (
                            <div style={{ marginTop: 8 }}>
                              <div style={{ fontWeight: 'bold', marginBottom: 8 }}>审批意见:</div>
                              <div style={{ padding: '8px 12px', background: '#f5f5f5', borderRadius: '4px' }}>
                                {selectedInvoice.remark}
                              </div>
                            </div>
                          )
                        },
                        {
                          title: '审批完成',
                          description: (
                            <div>
                              <div>{selectedInvoice.status === '已通过' ? '审批通过' : selectedInvoice.status === '已拒绝' ? '审批拒绝' : '等待审批'}</div>
                              {selectedInvoice.approveTime && (
                                <div style={{ color: '#999', fontSize: 12 }}>{selectedInvoice.approveTime}</div>
                              )}
                            </div>
                          ),
                          status: selectedInvoice.status === '已通过' ? 'finish' : selectedInvoice.status === '已拒绝' ? 'error' : 'wait'
                        }
                      ]}
                    />
                  </div>
                </div>
              </Card>
            ) : (
              <Card 
                bordered={false}
                style={{ 
                  boxShadow: '0 1px 3px rgba(0,0,0,0.1)', 
                  height: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}
              >
                <div style={{ textAlign: 'center', color: '#999' }}>
                  <AuditOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                  <div>请从左侧列表选择一个审批发票</div>
                </div>
              </Card>
            )}
          </div>
        </div>
      </Card>

      {/* 详情/审批对话框 */}
      <Modal
        title={currentInvoice?.status === '待审批' ? '开票审批' : '开票详情'}
        visible={modalVisible}
        onOk={currentInvoice?.status === '待审批' ? handleSubmit : undefined}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        width={800}
        destroyOnClose
        footer={currentInvoice?.status === '待审批' ? undefined : null}
      >
        {currentInvoice && (
          <div>
            <Descriptions bordered column={2} style={{ marginBottom: 16 }}>
              <Descriptions.Item label="发票编号">{currentInvoice.invoiceNo}</Descriptions.Item>
              <Descriptions.Item label="项目名称">{currentInvoice.projectName}</Descriptions.Item>
              <Descriptions.Item label="项目编码">{currentInvoice.projectCode}</Descriptions.Item>
              <Descriptions.Item label="客户名称">{currentInvoice.customerName}</Descriptions.Item>
              <Descriptions.Item label="发票类型">{currentInvoice.invoiceType}</Descriptions.Item>
              <Descriptions.Item label="发票金额">¥{currentInvoice.invoiceAmount.toLocaleString()}</Descriptions.Item>
              <Descriptions.Item label="税率">{(currentInvoice.taxRate * 100).toFixed(1)}%</Descriptions.Item>
              <Descriptions.Item label="税额">¥{currentInvoice.taxAmount.toLocaleString()}</Descriptions.Item>
              <Descriptions.Item label="总金额">
                <Text strong>¥{currentInvoice.totalAmount.toLocaleString()}</Text>
              </Descriptions.Item>
              <Descriptions.Item label="申请人">{currentInvoice.applicant}</Descriptions.Item>
              <Descriptions.Item label="申请时间">{currentInvoice.applyTime}</Descriptions.Item>
              <Descriptions.Item label="审批人">{currentInvoice.approver || '-'}</Descriptions.Item>
              <Descriptions.Item label="审批时间">{currentInvoice.approveTime || '-'}</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={currentInvoice.status === '待审批' ? 'orange' : 
                           currentInvoice.status === '已通过' ? 'green' : 'red'}>
                  {currentInvoice.status}
                </Tag>
              </Descriptions.Item>
            </Descriptions>

            {currentInvoice.attachments && currentInvoice.attachments.length > 0 && (
              <div style={{ marginBottom: 16 }}>
                <Title level={5}>相关附件</Title>
                <Space wrap>
                  {currentInvoice.attachments.map((file, index) => (
                    <Button key={index} type="link" icon={<FileTextOutlined />}>
                      {file}
                    </Button>
                  ))}
                </Space>
              </div>
            )}

            {currentInvoice.rejectReason && (
              <div style={{ marginBottom: 16 }}>
                <Title level={5}>拒绝原因</Title>
                <Text type="danger">{currentInvoice.rejectReason}</Text>
              </div>
            )}

            {currentInvoice.status === '待审批' && (
              <Form form={form} layout="vertical">
                <Form.Item
                  label="审批意见"
                  name="remark"
                  rules={[{ required: true, message: '请输入审批意见' }]}
                >
                  <TextArea rows={4} placeholder="请输入审批意见" />
                </Form.Item>
                <Form.Item name="action" hidden>
                  <Input />
                </Form.Item>
              </Form>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default InvoiceApproval;
